package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"ppa/config/db"
)

var SqlDB *gorm.DB

func Init(config db.Config) {
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",config.User,config.Pass,config.Host,config.Port,config.DbName)
	SqlDB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   config.Prefix,
			SingularTable: true,
		},
		Logger: logger.Default.LogMode(logger.Silent),
	})
	db, err := SqlDB.DB()
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(80)
	if err != nil {
		log.Fatal(err.Error())
	}
}

func RegistTable(dst ...interface{}) {
	err := SqlDB.AutoMigrate(dst...)
	if err != nil {
		log.Fatal(err.Error())
		return
	}
}
